//
//  MXHomeController.m
//  HNBaseProject
//
//  Created by xujie on 2024/5/31.
//

#import "MXHomeController.h"
#import "MXHomeNoticeView.h"
#import "MXHomeNavView.h"
#import "MXHomeSetFoodView.h"
#import "MXAddEquipmentController.h"
#import "MXVisibleFooderController.h"
#import "MXMessageCenterController.h"
#import "MXHomeSubController.h"
#import "MXNormalFooderController.h"
#import "MXHomeManageView.h"
#import "zhPopupController.h"
#import "MXHomeModel.h"
#import "MXHomeListCell.h"
#import "MXHomeListModel.h"
#import "MXHomeListController.h"
#import "DHNoDataView.h"

@interface MXHomeController () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView         *listTab;
@property (nonatomic, strong) UIButton *homeBtn;
@property (nonatomic, strong) MXHomeNoticeView *noticeV;
@property (nonatomic, strong) UIImageView *addImageV;
@property (nonatomic, strong) UIButton *equipmentBtn;
@property (nonatomic, strong) UIImageView *batteryIcon;
@property (nonatomic, strong) MXHomeModel *homeModel;
@property (nonatomic, strong) NSMutableArray *listArray;
@property (nonatomic, strong) NSMutableArray *homeArray;

@property (nonatomic,strong) DHNoDataView * noDataView;
@end

@implementation MXHomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor dc_colorWithHexString:@"#ebf4f8"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadList) name:@"updatehomename" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeCurrentHome:) name:@"enterhome" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadListAndChangeFamily:) name:@"enterNewFamily" object:nil];
    
    
    
    self.homeModel = [[MXHomeModel alloc] init];
    self.listArray = [[NSMutableArray alloc] init];
    self.homeArray = [[NSMutableArray alloc] init];
    [self createUI];
    [self getUserHomeInfo:nil];
}

#pragma mark - ________ UI ________

- (void)createUI {
    
    //我的家按钮
    [self.view addSubview:self.homeBtn];
    [self.homeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(20);
        make.top.offset(kStatusBarHeight+2);
        make.height.mas_equalTo(40);
        make.width.mas_lessThanOrEqualTo(kScreenW - 130);
    }];
    [self.homeBtn dc_buttonIconRightWithSpacing:8];
    
    //添加
    [self.view addSubview:self.addImageV];
    [self.addImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.mas_equalTo(35);
        make.centerY.mas_equalTo(self.homeBtn);
        make.right.offset(-15);
    }];
    //消息
    [self.view addSubview:self.noticeV];
    [self.noticeV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.mas_equalTo(35);
        make.centerY.mas_equalTo(self.homeBtn);
        make.right.mas_equalTo(self.addImageV.mas_left).offset(-5);
    }];
    
    MJWeakSelf;
    //上面的背景
    MXHomeNavView *bgView = [[MXHomeNavView alloc] init];
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(15);
        make.right.offset(-15);
        make.top.mas_equalTo(self.homeBtn.mas_bottom).offset(20);
        make.height.mas_equalTo(71);
    }];
    bgView.cellClick = ^(NSInteger index) {
        [weakSelf gotoSubVCWithIndex:index];
    };
    //设备按钮
    self.equipmentBtn = [UIButton buttonWithType:0];
    [self.equipmentBtn setTitle:@"设备" forState:0];
    [self.equipmentBtn setTitleColor:[UIColor dc_colorWithHexString:@"#000000"] forState:0];
    self.equipmentBtn.titleLabel.font = PFRFontMedium(13);
    [self.equipmentBtn setImage:[UIImage imageNamed:@"home_equip"] forState:0];
    [self.view addSubview:self.equipmentBtn];
    [self.equipmentBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(45);
        make.right.offset(-27);
        make.height.mas_equalTo(14);
        make.top.mas_equalTo(bgView.mas_bottom).offset(12);
    }];
    
    [self.equipmentBtn dc_buttonIconRightWithSpacing:5];
    
    [self.view addSubview:self.noDataView];
    [self.noDataView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.top.mas_equalTo(self.equipmentBtn.mas_bottom).offset(7);
    }];
    
    [self.view addSubview:self.listTab];
    [self.listTab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.top.mas_equalTo(self.equipmentBtn.mas_bottom).offset(7);
    }];
}

#pragma mark - ________ UITableView ________

- (UITableView *)listTab {
    
    if (nil == _listTab) {
        _listTab = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _listTab.backgroundColor = [UIColor clearColor];
        _listTab.separatorStyle = UITableViewCellSeparatorStyleNone;
        _listTab.delegate = self;
        _listTab.dataSource = self;
        _listTab.rowHeight = 288.0;
        _listTab.showsVerticalScrollIndicator = NO;
        _listTab.showsHorizontalScrollIndicator= NO;
        [_listTab registerClass:[MXHomeListCell class] forCellReuseIdentifier:NSStringFromClass([MXHomeListCell class])];
        if (@available(iOS 11.0, *)) {
            _listTab.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        if (@available(iOS 15.0, *)) {
            _listTab.sectionHeaderTopPadding = 0;
        }
        _listTab.contentInset = UIEdgeInsetsMake(0, 0, 20, 0);
        WEAKSELF;
        _listTab.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf getUserHomeInfo:weakSelf.homeModel?weakSelf.homeModel.familyId:nil];
        }];
    }
    return _listTab;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MJWeakSelf
    MXHomeListModel *model = self.listArray[indexPath.row];
    MXHomeListCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MXHomeListCell class])];
    [cell reloadCellWithModel:model];
//    cell.memberLab.text = [NSString stringWithFormat:@"%lu",(unsigned long)self.homeModel.familyMemberList.count];
    cell.setFoodV.setClick = ^{
        [weakSelf setOutFood];
    };
    return cell;
   
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.listArray.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MXHomeListModel *model = self.listArray[indexPath.row];
    MXVisibleFooderController *fooderVc = [[MXVisibleFooderController alloc] init];
    fooderVc.model = model;
    [self.navigationController pushViewController:fooderVc animated:YES];
}

#pragma mark - ________ lazy ________

- (UIButton *)homeBtn {
    if (!_homeBtn) {
        _homeBtn = [UIButton buttonWithType:0];
        [_homeBtn setTitle:@"我的家" forState:0];
        [_homeBtn setTitleColor:[UIColor dc_colorWithHexString:@"#000000"] forState:0];
        _homeBtn.titleLabel.font = PFRFontMedium(16);
        [_homeBtn setImage:[UIImage imageNamed:@"home_down"] forState:0];
        [_homeBtn addTarget:self action:@selector(tapMyHome) forControlEvents:UIControlEventTouchUpInside];
        _homeBtn.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    }
    return _homeBtn;
}

- (MXHomeNoticeView *)noticeV {
    if (!_noticeV) {
        _noticeV = [[MXHomeNoticeView alloc] init];
        MJWeakSelf;
        [_noticeV addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
            [weakSelf tapMessageView];
        }]];
        
    }
    return _noticeV;
}

- (UIImageView *)addImageV {
    if (!_addImageV) {
        _addImageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home_add"]];
        _addImageV.userInteractionEnabled = YES;
        _addImageV.contentMode = UIViewContentModeCenter;
        MJWeakSelf;
        [_addImageV addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
            [weakSelf tapAdd];
        }]];
    }
    return _addImageV;
}

#pragma mark - ________ Action ________

//我的家
- (void)tapMyHome {
    
    MXHomeManageView *aleartV = [[MXHomeManageView alloc] init];
    [aleartV realodViewWithHomeArray:self.homeArray withId:self.homeModel.familyId];
    zhPopupController *zh_popupController = [[zhPopupController alloc] initWithView:aleartV size:aleartV.bounds.size];
    zh_popupController.presentationStyle = zhPopupSlideStyleFade;
    zh_popupController.layoutType = zhPopupLayoutTypeTop;
    zh_popupController.dismissOnMaskTouched = YES;
    zh_popupController.offsetSpacing = kStatusBarHeight + 30 +20;
    [zh_popupController showInView:self.view duration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut bounced:NO completion:nil];
    
    
    MJWeakSelf
    aleartV.manageClick = ^{
        [zh_popupController dismiss];
        MXHomeListController *listVc = [[MXHomeListController alloc] init];
        [weakSelf.navigationController pushViewController:listVc animated:YES];
    };
    aleartV.dismissClick = ^{
        [zh_popupController dismiss];
    };
}

//点击消息
- (void)tapMessageView {
    MXMessageCenterController *messageVc = [[MXMessageCenterController alloc] init];
    [self.navigationController pushViewController:messageVc animated:YES];
}
//点击添加

- (void)tapAdd {
    if(self.homeModel && self.homeModel.familyId){
        MXAddEquipmentController *eVc = [[MXAddEquipmentController alloc] init];
        eVc.familyId = self.homeModel.familyId;
        [self.navigationController pushViewController:eVc animated:YES];
    }else{
        [SVProgressHUD showInfoWithStatus:@"家庭信息错误"];
    }
    
}

//导航跳转
- (void)gotoSubVCWithIndex:(NSInteger)index {
    MXHomeSubController *subVc = [[MXHomeSubController alloc] init];
    [self.navigationController pushViewController:subVc animated:YES];
    if (index== 0) {
        //喂食建议
    } else if (index == 1) {
        //提醒
    } else if (index == 2) {
        //社区
    }else if (index == 3) {
        //商城
    }
}

- (void)setOutFood {
    
}

- (void)reloadList {
    [self getUserHomeInfo:self.homeModel?self.homeModel.familyId:nil];
}
//从消息中点击进入新的家庭
-(void)reloadListAndChangeFamily:(NSNotification*)notification{
    NSLog(@"===reloadListAndChangeFamily%@",notification.object);
    NSString * familyId = notification.object;
    [self getUserHomeInfo:familyId];
}
 
//切换当前家庭
- (void)changeCurrentHome:(NSNotification*)notification {
    if (self.homeArray.count == 0) {
        return;
    }
    NSDictionary *dict = notification.object;
    NSString *familyId = dict[@"familyId"];
    MXHomeModel *currentModel = [[MXHomeModel alloc] init];
    for (int i = 0; i < self.homeArray.count; i++) {
        MXHomeModel *model = self.homeArray[i];
        if ([model.familyId isEqualToString:familyId]) {
            currentModel = model;
            self.homeModel = model;
        }
    }
    [self.listArray removeAllObjects];
    [self.homeBtn setTitle:currentModel.familyName forState:0];
    [self.homeBtn dc_buttonIconRightWithSpacing:8];

    if (currentModel.deviceList.count >0) {
        [self.listArray addObjectsFromArray:currentModel.deviceList];
    }
    [self.listTab reloadData];
    
    self.noDataView.hidden = self.listArray.count > 0;
}

#pragma mark - ________ NetWorking ________
//获取用户家庭信息
- (void)getUserHomeInfo:(NSString *)oldFamilyId{
    MJWeakSelf
    [self.view makeToastActivity];
    [[DCHttpClient shareClient] requestWithPath:@"api/app/appUser/userFamily" params:@{} httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        [weakSelf.listTab.mj_header endRefreshing];
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
            [weakSelf.homeArray removeAllObjects];
            [weakSelf.listArray removeAllObjects];
            NSArray *data = dict[@"data"];
            if (data.count > 0) {
                NSArray *dataArray =  [NSArray modelArrayWithClass:[MXHomeModel class] json:dict[@"data"]];
                [weakSelf.homeArray addObjectsFromArray:dataArray];
                for (MXHomeModel * homeModel in weakSelf.homeArray) {
                    for (MXHomeListModel * listModel in homeModel.deviceList) {
                        listModel.deviceForFamilyMemberCount = homeModel.familyMemberList.count;
                    }
                }
                
                if(oldFamilyId && oldFamilyId.length > 0){
                    for (MXHomeModel * model in weakSelf.homeArray) {
                        if([model.familyId isEqualToString:oldFamilyId]){
                            weakSelf.homeModel = model;
                            [weakSelf.homeBtn setTitle:weakSelf.homeModel.familyName forState:0];
                            [weakSelf.homeBtn dc_buttonIconRightWithSpacing:8];
                            [weakSelf.listArray removeAllObjects];
                            if (weakSelf.homeModel.deviceList.count >0) {
                                [weakSelf.listArray addObjectsFromArray:weakSelf.homeModel.deviceList];
                                [weakSelf.listTab reloadData];
                            }
                            
                        }
                    }
                }else{
                    weakSelf.homeModel =  weakSelf.homeArray.firstObject;
    //                CGSize nameSize = [weakSelf.homeModel.familyName sizeWithFont:PFRFontMedium(16) maxSize:CGSizeMake(300, 20)];
                    [weakSelf.homeBtn setTitle:weakSelf.homeModel.familyName forState:0];
                    [weakSelf.homeBtn dc_buttonIconRightWithSpacing:8];
                    [weakSelf.listArray removeAllObjects];
                    if (weakSelf.homeModel.deviceList.count >0) {
                        [weakSelf.listArray addObjectsFromArray:weakSelf.homeModel.deviceList];
                        [weakSelf.listTab reloadData];
                    }
                }
                
                weakSelf.noDataView.hidden = weakSelf.listArray.count > 0;
                
                //获取家庭设备
//                [weakSelf getDeviceCountWithId:weakSelf.homeModel.familyId];
//                [weakSelf registerDevice];
            }
        } else {

            [weakSelf.view xjmakeToast:dict[DC_ResultMsg_Key]];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
        [weakSelf.listTab.mj_header endRefreshing];
    }];
}

- (void)getDeviceCountWithId:(NSString *)familyId {
    NSDictionary *param = @{@"familyId":self.homeModel.familyId};
    MJWeakSelf
    [[DCHttpClient shareClient] requestWithPath:@"api/app/device/listByFamily" params:param httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
            [weakSelf.listArray removeAllObjects];
            
            
            NSArray *dataArray =  [NSArray modelArrayWithClass:[MXHomeListModel class] json:dict[@"data"]];
            [weakSelf.listArray addObjectsFromArray:dataArray];
            [weakSelf.listTab reloadData];
            
        } else {
            
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    }];
}


//- (void)queryCategoryList {
//    [[DCHttpClient shareClient] requestWithPath:@"api/app/appDeviceCategory/queryCategoryList" params:@{@"pageNum":@"1",@"pageSize":@"20"} httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
//        NSDictionary * dict = [responseObject mj_JSONObject];
//        
//        if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
//            
//        } else {
//            
//        }
//    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
//        
//    }];
//}

//测试注册设备
- (void)registerDevice {
    NSDictionary *param = @{@"familyId":self.homeModel.familyId,
                            @"macAddress":@"AA:BB:CC:DD:06",
                            @"categoryId":@"1",
                            @"deviceLocalName":@"138设备",
                            @"linkAccount":@"13856696072",
                            @"linkPassword":@"123456"
    };
    MJWeakSelf
    [self.view makeToastActivity];
    [[DCHttpClient shareClient] requestWithPath:@"api/app/device/register" params:param httpMethod:DCHttpRequestPost sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
            [weakSelf.view xjmakeToast:dict[DC_ResultMsg_Key]];
        } else {
            [weakSelf.view xjmakeToast:dict[DC_ResultMsg_Key]];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self dc_navBarHidden:YES];
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


-(DHNoDataView *)noDataView{
    if(!_noDataView){
        _noDataView = [[DHNoDataView alloc] init];
        _noDataView.hidden = YES;
        _noDataView.noDataLabel.text = @"暂无设备";
    }
    return _noDataView;
}

@end
